import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../models/task.dart';
import '../theme/app_theme.dart';
import 'add_task_page.dart';
import 'pending_tasks_page.dart';
import 'task_detail_page.dart';

// 视图模式：月视图、周视图、日视图
enum ViewMode { month, week, day }

class SchedulePage extends StatefulWidget {
  final List<Task> tasks;
  final Function(Task) onTaskUpdate;
  final Function(Task) onTaskDelete;

  const SchedulePage({
    Key? key,
    required this.tasks,
    required this.onTaskUpdate,
    required this.onTaskDelete,
  }) : super(key: key);

  @override
  _SchedulePageState createState() => _SchedulePageState();
}

class _SchedulePageState extends State<SchedulePage> with AppTheme, TickerProviderStateMixin {
  // 当前视图模式
  ViewMode _currentViewMode = ViewMode.month;
  final _taskController = TextEditingController();
  final _noteController = TextEditingController();
  String _filterStatus = 'all'; // 'all', 'pending', 'completed', 'deleted'

  // 当前选中的日期
  late DateTime _selectedDate;
  // 当前显示的月份
  late DateTime _currentMonth;
  // 当前显示的周
  late DateTime _currentWeek;
  
  // 动画控制器
  late AnimationController _animationController;
  late Animation<double> _fadeAnimation;
  late Animation<Offset> _slideAnimation;

  // 获取任务数据
  List<Task> get _tasks => widget.tasks;

  @override
  void initState() {
    super.initState();
    _selectedDate = DateTime.now();
    _currentMonth = DateTime(_selectedDate.year, _selectedDate.month, 1);
    _currentWeek = _selectedDate.subtract(Duration(days: _selectedDate.weekday % 7));
    
    // 初始化动画
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 1000),
    );
    
    _fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: _animationController,
        curve: const Interval(0.0, 0.6, curve: Curves.easeOut),
      ),
    );
    
    _slideAnimation = Tween<Offset>(
      begin: const Offset(0, -0.3),
      end: Offset.zero,
    ).animate(
      CurvedAnimation(
        parent: _animationController,
        curve: const Interval(0.2, 0.8, curve: Curves.easeOutCubic),
      ),
    );
    
    _animationController.forward();
  }

  @override
  void dispose() {
    _animationController.dispose();
    _taskController.dispose();
    _noteController.dispose();
    super.dispose();
  }

  // 获取某月的天数
  int _getDaysInMonth(DateTime date) {
    return DateTime(date.year, date.month + 1, 0).day;
  }

  // 获取某月第一天是星期几
  int _getFirstWeekdayOfMonth(DateTime date) {
    return DateTime(date.year, date.month, 1).weekday;
  }

  // 获取某天的任务
  List<Task> _getTasksForDate(DateTime date) {
    final tasks = _tasks.where((task) {
      final taskDate = DateTime(task.time.year, task.time.month, task.time.day);
      final checkDate = DateTime(date.year, date.month, date.day);
      return taskDate.isAtSameMomentAs(checkDate);
    }).toList();

    switch (_filterStatus) {
      case 'pending':
        return tasks.where((task) => !task.isCompleted && !task.isDeleted).toList();
      case 'completed':
        return tasks.where((task) => task.isCompleted && !task.isDeleted).toList();
      case 'deleted':
        return tasks.where((task) => task.isDeleted).toList();
      default: // 'all'
        return tasks.where((task) => !task.isDeleted).toList();
    }
  }

  // 获取当前是第几周
  int _getWeekNumber(DateTime date) {
    final firstDayOfMonth = DateTime(date.year, date.month, 1);
    final firstWeekday = firstDayOfMonth.weekday;
    final dayOfMonth = date.day;
    return ((dayOfMonth + firstWeekday - 2) ~/ 7) + 1;
  }

  // 返回今天
  void _goToToday() {
    setState(() {
      final today = DateTime.now();
      _selectedDate = today;
      _currentMonth = DateTime(today.year, today.month, 1);
      _currentWeek = today.subtract(Duration(days: today.weekday % 7));
    });
  }

  // 切换视图模式
  void _changeViewMode(ViewMode mode) {
    setState(() {
      _currentViewMode = mode;
      // 根据当前选中的日期更新月份和周
      if (mode == ViewMode.month) {
        _currentMonth = DateTime(_selectedDate.year, _selectedDate.month, 1);
      } else if (mode == ViewMode.week) {
        _currentWeek = _selectedDate.subtract(Duration(days: _selectedDate.weekday % 7));
      }
    });
  }

  // 切换月份
  void _changeMonth(int delta) {
    setState(() {
      _currentMonth = DateTime(
        _currentMonth.year,
        _currentMonth.month + delta,
        1,
      );
    });
  }

  // 切换周
  void _changeWeek(int delta) {
    setState(() {
      _currentWeek = _currentWeek.add(Duration(days: 7 * delta));
    });
  }

  // 切换日期
  void _changeDate(int delta) {
    setState(() {
      _selectedDate = _selectedDate.add(Duration(days: delta));
    });
  }

  // 获取统计数据
  Map<String, int> _getStatistics() {
    List<Task> tasksInRange = [];
    
    if (_currentViewMode == ViewMode.month) {
      final startDate = DateTime(_currentMonth.year, _currentMonth.month, 1);
      final endDate = DateTime(_currentMonth.year, _currentMonth.month + 1, 0);
      tasksInRange = _tasks.where((task) {
        final taskDate = DateTime(task.time.year, task.time.month, task.time.day);
        return taskDate.isAfter(startDate.subtract(const Duration(days: 1))) && 
               taskDate.isBefore(endDate.add(const Duration(days: 1)));
      }).toList();
    } else if (_currentViewMode == ViewMode.week) {
      final startDate = _currentWeek;
      final endDate = _currentWeek.add(const Duration(days: 6));
      tasksInRange = _tasks.where((task) {
        final taskDate = DateTime(task.time.year, task.time.month, task.time.day);
        return taskDate.isAfter(startDate.subtract(const Duration(days: 1))) && 
               taskDate.isBefore(endDate.add(const Duration(days: 1)));
      }).toList();
    } else {
      // 日视图
      tasksInRange = _getTasksForDate(_selectedDate);
    }

    final total = tasksInRange.where((task) => !task.isDeleted).length;
    final completed = tasksInRange.where((task) => task.isCompleted && !task.isDeleted).length;
    final pending = tasksInRange.where((task) => !task.isCompleted && !task.isDeleted).length;
    final deleted = tasksInRange.where((task) => task.isDeleted).length;

    return {
      'total': total,
      'completed': completed,
      'pending': pending,
      'deleted': deleted,
    };
  }

  // 统计卡片
  Widget _buildStatisticsCards() {
    final stats = _getStatistics();
    final total = stats['total']!;
    final completed = stats['completed']!;
    final pending = stats['pending']!;
    final deleted = stats['deleted']!;
    final completionRate = total > 0 ? (completed / total * 100).round() : 0;

    return SlideTransition(
      position: _slideAnimation,
      child: FadeTransition(
        opacity: _fadeAnimation,
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: AppTheme.paddingS),
      child: Row(
        children: [
          Expanded(
            child: _buildStatCard(
              '总任务',
              '$total',
                  AppTheme.infoColor,
                  Icons.list_alt_rounded,
                  LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [AppTheme.infoColor, Color(0xFF2563EB)],
                  ),
            ),
          ),
              const SizedBox(width: AppTheme.paddingS),
          Expanded(
            child: _buildStatCard(
              '已完成',
              '$completed',
                  AppTheme.successColor,
                  Icons.check_circle_rounded,
                  AppTheme.successGradient,
            ),
          ),
              const SizedBox(width: AppTheme.paddingS),
          Expanded(
            child: GestureDetector(
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => PendingTasksPage(
                      tasks: widget.tasks,
                      onTaskUpdate: widget.onTaskUpdate,
                    ),
                  ),
                );
              },
              child: _buildStatCard(
                '待完成',
                '$pending',
                    AppTheme.warningColor,
                    Icons.schedule_rounded,
                    AppTheme.warningGradient,
              ),
            ),
          ),
              const SizedBox(width: AppTheme.paddingS),
          Expanded(
            child: _buildStatCard(
              '完成率',
              '$completionRate%',
                  AppTheme.primaryColor,
                  Icons.pie_chart_rounded,
                  AppTheme.primaryGradient,
            ),
          ),
        ],
          ),
        ),
      ),
    );
  }

  // 单个统计卡片
  Widget _buildStatCard(String title, String value, Color color, IconData icon, LinearGradient gradient) {
    return Container(
      padding: const EdgeInsets.all(AppTheme.paddingL),
      decoration: BoxDecoration(
        color: AppTheme.cardColor,
        borderRadius: BorderRadius.circular(AppTheme.radiusL),
        boxShadow: AppTheme.softShadow,
        border: Border.all(
          color: color.withOpacity(0.2),
          width: 1,
        ),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            padding: const EdgeInsets.all(AppTheme.paddingS),
            decoration: BoxDecoration(
              gradient: gradient,
              borderRadius: BorderRadius.circular(AppTheme.radiusM),
              boxShadow: [
                BoxShadow(
                  color: color.withOpacity(0.3),
                  blurRadius: 8,
                  offset: const Offset(0, 4),
                ),
              ],
            ),
            child: Icon(
            icon,
              color: Colors.white,
              size: 20,
          ),
          ),
          const SizedBox(height: AppTheme.paddingS),
          Text(
            value,
            style: TextStyle(
              fontSize: AppTheme.fontSizeL,
              fontWeight: FontWeight.w700,
              color: color,
            ),
          ),
          const SizedBox(height: AppTheme.paddingXS),
          Text(
            title,
            style: const TextStyle(
              fontSize: AppTheme.fontSizeXS,
              color: AppTheme.textSecondaryColor,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
    );
  }

  // 添加新任务
  void _addNewTask() async {
    final newTask = await Navigator.push<Task>(
      context,
      MaterialPageRoute(
        builder: (context) => const AddTaskPage(),
      ),
    );
    
    if (newTask != null) {
      // 如果任务没有指定特定的日期，则设置为当前选中的日期
      final updatedTask = Task(
        id: newTask.id,
        title: newTask.title,
        time: DateTime(
          _selectedDate.year,
          _selectedDate.month,
          _selectedDate.day,
          newTask.time.hour,
          newTask.time.minute,
        ),
        priority: newTask.priority,
        location: newTask.location,
        category: newTask.category,
        note: newTask.note,
        isCompleted: newTask.isCompleted,
        isDeleted: newTask.isDeleted,
      );
      widget.onTaskUpdate(updatedTask);
    }
  }

  // 获取日期状态颜色
  Color _getDateColor(DateTime date, List<Task> tasks) {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    final dateToCheck = DateTime(date.year, date.month, date.day);
    
    final isToday = dateToCheck.isAtSameMomentAs(today);
    final isPast = dateToCheck.isBefore(today);
    final isFuture = dateToCheck.isAfter(today);

    if (isToday) {
      return tasks.isEmpty ? Colors.yellow[100]! : Colors.orange[100]!;
    }

    if (isPast) {
      // 过去的日期：有未完成任务显示红色，没有未完成任务（即所有任务都已完成）显示绿色
      return tasks.isEmpty ? Colors.green[100]! : Colors.red[100]!;
    }

    if (isFuture) {
      return tasks.isEmpty ? Colors.grey[200]! : Colors.blue[100]!;
    }

    return Colors.grey[200]!;
  }

  // 完成任务
  void _completeTask(Task task) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('完成任务'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text('任务：${task.title}'),
            const SizedBox(height: 16),
            TextField(
              controller: _noteController,
              decoration: const InputDecoration(
                hintText: '添加备注（可选）',
                border: OutlineInputBorder(),
              ),
              maxLines: 3,
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () {
              _noteController.clear();
              Navigator.pop(context);
            },
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              task.isCompleted = true;
              task.completedTime = DateTime.now();
              task.note = _noteController.text.isNotEmpty ? _noteController.text : null;
              widget.onTaskUpdate(task);
              _noteController.clear();
              Navigator.pop(context);
            },
            child: const Text('完成'),
          ),
        ],
      ),
    );
  }

  // 恢复任务
  void _restoreTask(Task task) {
    task.isDeleted = false;
    task.isCompleted = false;
    task.completedTime = null;
    task.note = null; // 清除备注
    widget.onTaskUpdate(task);
  }

  // 删除任务（永久）
  void _deleteTaskPermanently(Task task) {
    widget.onTaskDelete(task);
  }

  // 软删除任务
  void _softDeleteTask(Task task) {
    task.isDeleted = true;
    widget.onTaskUpdate(task);
  }

  // 查看备注
  void _viewNote(Task task) {
    if (task.note != null) {
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: const Text('任务备注'),
          content: Text(task.note!),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('关闭'),
            ),
          ],
        ),
      );
    }
  }

  // 任务筛选按钮
  Widget _buildTaskFilter() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: AppTheme.paddingL),
      padding: const EdgeInsets.all(AppTheme.paddingS),
      decoration: BoxDecoration(
        color: AppTheme.cardColor,
        borderRadius: BorderRadius.circular(AppTheme.radiusL),
        boxShadow: AppTheme.softShadow,
      ),
      child: SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: Row(
        children: [
            _buildFilterButton('全部', 'all', Icons.list_alt_rounded),
            const SizedBox(width: AppTheme.paddingS),
            _buildFilterButton('未完成', 'pending', Icons.schedule_rounded),
            const SizedBox(width: AppTheme.paddingS),
            _buildFilterButton('已完成', 'completed', Icons.check_circle_rounded),
            const SizedBox(width: AppTheme.paddingS),
            _buildFilterButton('已删除', 'deleted', Icons.delete_rounded),
        ],
        ),
      ),
    );
  }

  // 单个筛选按钮
  Widget _buildFilterButton(String text, String status, IconData icon) {
    final isSelected = _filterStatus == status;
    Color color;
    LinearGradient? gradient;
    
    switch (status) {
      case 'pending':
        color = AppTheme.warningColor;
        gradient = isSelected ? AppTheme.warningGradient : null;
        break;
      case 'completed':
        color = AppTheme.successColor;
        gradient = isSelected ? AppTheme.successGradient : null;
        break;
      case 'deleted':
        color = AppTheme.errorColor;
        gradient = isSelected ? LinearGradient(
          colors: [AppTheme.errorColor, Color(0xFFDC2626)],
        ) : null;
        break;
      default: // 'all'
        color = AppTheme.primaryColor;
        gradient = isSelected ? AppTheme.primaryGradient : null;
    }
    
    return Material(
      color: Colors.transparent,
      child: InkWell(
        borderRadius: BorderRadius.circular(AppTheme.radiusXL),
      onTap: () {
        setState(() {
          _filterStatus = status;
        });
      },
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeInOut,
          padding: const EdgeInsets.symmetric(
            horizontal: AppTheme.paddingL,
            vertical: AppTheme.paddingM,
          ),
        decoration: BoxDecoration(
            gradient: gradient,
            color: isSelected ? null : color.withOpacity(0.1),
            borderRadius: BorderRadius.circular(AppTheme.radiusXL),
          border: Border.all(
              color: isSelected ? Colors.transparent : color.withOpacity(0.3),
            width: 1,
          ),
            boxShadow: isSelected ? [
              BoxShadow(
                color: color.withOpacity(0.3),
                blurRadius: 8,
                offset: const Offset(0, 4),
              ),
            ] : null,
        ),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(
                icon,
                color: isSelected ? Colors.white : color,
                size: 16,
              ),
              const SizedBox(width: AppTheme.paddingXS),
              Text(
          text,
          style: TextStyle(
                  color: isSelected ? Colors.white : color,
            fontSize: AppTheme.fontSizeS,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppTheme.backgroundColor,
      body: SafeArea(
        child: Column(
          children: [
            // 顶部容器
            Container(
              decoration: BoxDecoration(
                gradient: AppTheme.primaryGradient,
                boxShadow: AppTheme.strongShadow,
              ),
              child: Padding(
                padding: const EdgeInsets.all(AppTheme.paddingXL),
                child: SlideTransition(
                  position: _slideAnimation,
                  child: FadeTransition(
                    opacity: _fadeAnimation,
              child: Column(
                children: [
                        // 顶部标题和视图切换
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                            const Text(
                              '日程安排',
                              style: TextStyle(
                                fontSize: AppTheme.fontSizeXXL,
                                fontWeight: FontWeight.w700,
                                color: Colors.white,
                              ),
                            ),
                            Container(
                              padding: const EdgeInsets.all(AppTheme.paddingXS),
                              decoration: BoxDecoration(
                                color: Colors.white.withOpacity(0.15),
                                borderRadius: BorderRadius.circular(AppTheme.radiusL),
                              ),
                              child: Row(
                        children: [
                          _buildViewModeButton('月', ViewMode.month),
                                  const SizedBox(width: AppTheme.paddingXS),
                          _buildViewModeButton('周', ViewMode.week),
                                  const SizedBox(width: AppTheme.paddingXS),
                          _buildViewModeButton('日', ViewMode.day),
                        ],
                              ),
                      ),
                    ],
                  ),
                        const SizedBox(height: AppTheme.paddingL),
                  // 日期导航
                        Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: AppTheme.paddingL,
                            vertical: AppTheme.paddingM,
                          ),
                          decoration: BoxDecoration(
                            color: Colors.white.withOpacity(0.15),
                            borderRadius: BorderRadius.circular(AppTheme.radiusL),
                          ),
                          child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                              Material(
                                color: Colors.transparent,
                                child: InkWell(
                                  borderRadius: BorderRadius.circular(AppTheme.radiusM),
                                  onTap: () {
                          if (_currentViewMode == ViewMode.month) {
                            _changeMonth(-1);
                          } else if (_currentViewMode == ViewMode.week) {
                            _changeWeek(-1);
                          } else {
                            _changeDate(-1);
                          }
                        },
                                  child: Container(
                                    padding: const EdgeInsets.all(AppTheme.paddingS),
                                    decoration: BoxDecoration(
                                      color: Colors.white.withOpacity(0.2),
                                      borderRadius: BorderRadius.circular(AppTheme.radiusM),
                                    ),
                                    child: const Icon(
                                      Icons.chevron_left_rounded,
                                      color: Colors.white,
                                      size: 24,
                                    ),
                                  ),
                                ),
                      ),
                      Text(
                        _currentViewMode == ViewMode.month
                            ? DateFormat('yyyy年MM月').format(_currentMonth)
                            : _currentViewMode == ViewMode.week
                                ? '${DateFormat('M').format(_currentWeek)}月第${_getWeekNumber(_currentWeek)}周'
                                : DateFormat('yyyy年MM月dd日').format(_selectedDate),
                        style: const TextStyle(
                                  fontSize: AppTheme.fontSizeXL,
                                  fontWeight: FontWeight.w600,
                                  color: Colors.white,
                        ),
                      ),
                              Material(
                                color: Colors.transparent,
                                child: InkWell(
                                  borderRadius: BorderRadius.circular(AppTheme.radiusM),
                                  onTap: () {
                          if (_currentViewMode == ViewMode.month) {
                            _changeMonth(1);
                          } else if (_currentViewMode == ViewMode.week) {
                            _changeWeek(1);
                          } else {
                            _changeDate(1);
                          }
                        },
                                  child: Container(
                                    padding: const EdgeInsets.all(AppTheme.paddingS),
                                    decoration: BoxDecoration(
                                      color: Colors.white.withOpacity(0.2),
                                      borderRadius: BorderRadius.circular(AppTheme.radiusM),
                                    ),
                                    child: const Icon(
                                      Icons.chevron_right_rounded,
                                      color: Colors.white,
                                      size: 24,
                                    ),
                                  ),
                                ),
                      ),
                    ],
                  ),
                        ),
                        const SizedBox(height: AppTheme.paddingL),
                  // 统计卡片
                  _buildStatisticsCards(),
                ],
                    ),
                  ),
                ),
              ),
            ),

            // 主体内容
            Expanded(
              child: Stack(
                children: [
                  _currentViewMode == ViewMode.month
                      ? _buildMonthView()
                      : _currentViewMode == ViewMode.week
                          ? _buildWeekView()
                          : _buildDayView(),
                  if (_currentViewMode != ViewMode.day)
                    Positioned(
                      right: AppTheme.paddingL,
                      bottom: AppTheme.paddingL,
                      child: Container(
                        decoration: BoxDecoration(
                          gradient: AppTheme.successGradient,
                          borderRadius: BorderRadius.circular(AppTheme.radiusXXL),
                          boxShadow: AppTheme.mediumShadow,
                        ),
                        child: Material(
                          color: Colors.transparent,
                          child: InkWell(
                            borderRadius: BorderRadius.circular(AppTheme.radiusXXL),
                            onTap: _goToToday,
                            child: Container(
                              padding: const EdgeInsets.all(AppTheme.paddingL),
                              child: const Icon(
                                Icons.today_rounded,
                                color: Colors.white,
                                size: 24,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 视图模式切换按钮
  Widget _buildViewModeButton(String text, ViewMode mode) {
    final isSelected = _currentViewMode == mode;
    return Material(
      color: Colors.transparent,
      child: InkWell(
        borderRadius: BorderRadius.circular(AppTheme.radiusM),
      onTap: () => _changeViewMode(mode),
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeInOut,
          padding: const EdgeInsets.symmetric(
            horizontal: AppTheme.paddingM,
            vertical: AppTheme.paddingS,
          ),
        decoration: BoxDecoration(
            color: isSelected 
                ? Colors.white 
                : Colors.transparent,
            borderRadius: BorderRadius.circular(AppTheme.radiusM),
            boxShadow: isSelected ? [
              BoxShadow(
                color: Colors.black.withOpacity(0.1),
                blurRadius: 4,
                offset: const Offset(0, 2),
              ),
            ] : null,
        ),
        child: Text(
          text,
          style: TextStyle(
              color: isSelected ? AppTheme.primaryColor : Colors.white,
              fontWeight: FontWeight.w600,
              fontSize: AppTheme.fontSizeM,
            ),
          ),
        ),
      ),
    );
  }

  // 月视图
  Widget _buildMonthView() {
    final daysInMonth = _getDaysInMonth(_currentMonth);
    final firstWeekday = _getFirstWeekdayOfMonth(_currentMonth);
    final weeks = ((daysInMonth + firstWeekday - 1) / 7).ceil();
    final today = DateTime.now();

    return FadeTransition(
      opacity: _fadeAnimation,
      child: Container(
        margin: const EdgeInsets.all(AppTheme.paddingL),
        decoration: BoxDecoration(
          color: AppTheme.cardColor,
          borderRadius: BorderRadius.circular(AppTheme.radiusXL),
          boxShadow: AppTheme.mediumShadow,
        ),
        child: Column(
      children: [
        // 星期标题
        Container(
              padding: const EdgeInsets.symmetric(vertical: AppTheme.paddingL),
          decoration: BoxDecoration(
                color: AppTheme.primaryColor.withOpacity(0.05),
                borderRadius: const BorderRadius.only(
                  topLeft: Radius.circular(AppTheme.radiusXL),
                  topRight: Radius.circular(AppTheme.radiusXL),
                ),
            border: Border(
              bottom: BorderSide(
                    color: AppTheme.primaryColor.withOpacity(0.1),
                width: 1,
              ),
            ),
          ),
          child: Row(
            children: ['日', '一', '二', '三', '四', '五', '六'].map((day) {
                  final isWeekend = day == '日' || day == '六';
              return Expanded(
                child: Text(
                  day,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                        color: isWeekend ? AppTheme.primaryColor : AppTheme.textSecondaryColor,
                        fontWeight: FontWeight.w600,
                        fontSize: AppTheme.fontSizeM,
                  ),
                ),
              );
            }).toList(),
          ),
        ),

        // 日历网格
        Expanded(
              child: Padding(
                padding: const EdgeInsets.all(AppTheme.paddingS),
          child: GridView.builder(
                  physics: const NeverScrollableScrollPhysics(),
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 7,
              childAspectRatio: 1,
                    crossAxisSpacing: AppTheme.paddingXS,
                    mainAxisSpacing: AppTheme.paddingXS,
            ),
            itemCount: weeks * 7,
            itemBuilder: (context, index) {
              final day = index - firstWeekday + 1;
              final isCurrentMonth = day > 0 && day <= daysInMonth;
              final date = isCurrentMonth
                  ? DateTime(_currentMonth.year, _currentMonth.month, day)
                  : null;

              if (!isCurrentMonth) {
                return Container();
              }

              final tasks = date != null ? _getTasksForDate(date) : <Task>[];
              final isSelected = date != null &&
                  date.year == _selectedDate.year &&
                  date.month == _selectedDate.month &&
                  date.day == _selectedDate.day;
              final isToday = date != null &&
                  date.year == today.year &&
                  date.month == today.month &&
                  date.day == today.day;

                    return _buildDateCell(date!, tasks, isSelected, isToday);
                  },
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 日期单元格
  Widget _buildDateCell(DateTime date, List<Task> tasks, bool isSelected, bool isToday) {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    final dateToCheck = DateTime(date.year, date.month, date.day);
    
    final isPast = dateToCheck.isBefore(today);
    final isFuture = dateToCheck.isAfter(today);
    
    Color backgroundColor;
    Color textColor;
    Color borderColor;
    
    if (isToday) {
      backgroundColor = AppTheme.primaryColor.withOpacity(0.1);
      textColor = AppTheme.primaryColor;
      borderColor = AppTheme.primaryColor;
    } else if (isPast) {
      if (tasks.isEmpty) {
        backgroundColor = AppTheme.successColor.withOpacity(0.1);
        textColor = AppTheme.successColor;
        borderColor = AppTheme.successColor.withOpacity(0.3);
      } else {
        final hasUncompletedTasks = tasks.any((task) => !task.isCompleted && !task.isDeleted);
        if (hasUncompletedTasks) {
          backgroundColor = AppTheme.errorColor.withOpacity(0.1);
          textColor = AppTheme.errorColor;
          borderColor = AppTheme.errorColor.withOpacity(0.3);
        } else {
          backgroundColor = AppTheme.successColor.withOpacity(0.1);
          textColor = AppTheme.successColor;
          borderColor = AppTheme.successColor.withOpacity(0.3);
        }
      }
    } else if (isFuture) {
      if (tasks.isEmpty) {
        backgroundColor = AppTheme.cardColor;
        textColor = AppTheme.textSecondaryColor;
        borderColor = AppTheme.borderColor;
      } else {
        backgroundColor = AppTheme.infoColor.withOpacity(0.1);
        textColor = AppTheme.infoColor;
        borderColor = AppTheme.infoColor.withOpacity(0.3);
      }
    } else {
      backgroundColor = AppTheme.cardColor;
      textColor = AppTheme.textPrimaryColor;
      borderColor = AppTheme.borderColor;
    }

    return Material(
      color: Colors.transparent,
      child: InkWell(
        borderRadius: BorderRadius.circular(AppTheme.radiusL),
                onTap: () {
                    setState(() {
                      _selectedDate = date;
                      _currentViewMode = ViewMode.day;
                    });
                },
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 200),
                  decoration: BoxDecoration(
            color: backgroundColor,
            borderRadius: BorderRadius.circular(AppTheme.radiusL),
                    border: Border.all(
                      color: isSelected 
                  ? AppTheme.primaryColor
                  : borderColor,
                      width: isSelected ? 2 : 1,
                    ),
            boxShadow: isSelected ? [
              BoxShadow(
                color: AppTheme.primaryColor.withOpacity(0.2),
                blurRadius: 8,
                offset: const Offset(0, 4),
              ),
            ] : null,
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                date.day.toString(),
                style: TextStyle(
                  color: isSelected ? AppTheme.primaryColor : textColor,
                  fontWeight: isSelected || isToday ? FontWeight.w700 : FontWeight.w500,
                  fontSize: AppTheme.fontSizeM,
                        ),
                      ),
              if (tasks.isNotEmpty) ...[
                const SizedBox(height: AppTheme.paddingXS),
                        Container(
                          padding: const EdgeInsets.symmetric(
                    horizontal: AppTheme.paddingXS,
                            vertical: 2,
                          ),
                          decoration: BoxDecoration(
                    color: (isSelected ? AppTheme.primaryColor : textColor).withOpacity(0.2),
                    borderRadius: BorderRadius.circular(AppTheme.radiusXS),
                          ),
                          child: Text(
                    '${tasks.length}',
                    style: TextStyle(
                      fontSize: AppTheme.fontSizeXS,
                      color: isSelected ? AppTheme.primaryColor : textColor,
                      fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
              ],
                    ],
                  ),
                ),
          ),
    );
  }

  // 周视图
  Widget _buildWeekView() {
    final today = DateTime.now();

    return Column(
      children: [
        // 日期标题
        Container(
          padding: const EdgeInsets.symmetric(vertical: 8),
          decoration: BoxDecoration(
            color: Colors.grey[50],
            border: Border(
              bottom: BorderSide(
                color: Colors.grey[200]!,
                width: 1,
              ),
            ),
          ),
          child: Row(
            children: List.generate(7, (index) {
              final date = _currentWeek.add(Duration(days: index));
              final isToday = date.year == today.year &&
                  date.month == today.month &&
                  date.day == today.day;
              final isSelected = date.year == _selectedDate.year &&
                  date.month == _selectedDate.month &&
                  date.day == _selectedDate.day;
              final tasks = _getTasksForDate(date);
              final dateColor = _getDateColor(date, tasks);

              return Expanded(
                child: GestureDetector(
                  onTap: () {
                    setState(() {
                      _selectedDate = date;
                      _currentViewMode = ViewMode.day;
                    });
                  },
                  child: Container(
                    padding: const EdgeInsets.symmetric(vertical: 8),
                    decoration: BoxDecoration(
                      color: dateColor,
                      border: Border(
                        bottom: BorderSide(
                          color: isSelected 
                              ? HSLColor.fromColor(dateColor).withLightness(0.3).toColor()
                              : Colors.grey[300]!,
                          width: isSelected ? 2 : 1,
                        ),
                      ),
                    ),
                    child: Column(
                      children: [
                        Text(
                          ['日', '一', '二', '三', '四', '五', '六'][index],
                          style: const TextStyle(
                            color: Colors.black87,
                            fontSize: 12,
                          ),
                        ),
                        const SizedBox(height: 4),
                        Text(
                          date.day.toString(),
                          style: const TextStyle(
                            color: Colors.black87,
                            fontWeight: FontWeight.normal,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              );
            }),
          ),
        ),

        // 任务网格
        Expanded(
          child: Row(
            children: List.generate(7, (dayIndex) {
              final date = _currentWeek.add(Duration(days: dayIndex));
              final dayTasks = _getTasksForDate(date);
              final isToday = date.year == today.year &&
                  date.month == today.month &&
                  date.day == today.day;
              final isSelected = date.year == _selectedDate.year &&
                  date.month == _selectedDate.month &&
                  date.day == _selectedDate.day;
              final dateColor = _getDateColor(date, dayTasks);

              return Expanded(
                child: GestureDetector(
                  onTap: () {
                    setState(() {
                      _selectedDate = date;
                      _currentViewMode = ViewMode.day;
                    });
                  },
                  child: Container(
                    decoration: BoxDecoration(
                      border: Border(
                        right: BorderSide(
                          color: Colors.grey[200]!,
                          width: 1,
                        ),
                      ),
                      color: isToday 
                          ? Colors.green.withOpacity(0.05) 
                          : isSelected 
                              ? Colors.blue.withOpacity(0.05) 
                              : dateColor,
                    ),
                    child: Column(
                      children: [
                        // 任务卡片列表
                        Expanded(
                          child: dayTasks.isEmpty
                              ? Center(
                                  child: Text(
                                    '无任务',
                                    style: TextStyle(
                                      color: Colors.grey[400],
                                      fontSize: 12,
                                    ),
                                  ),
                                )
                              : ListView.builder(
                                  padding: const EdgeInsets.all(4),
                                  itemCount: dayTasks.length,
                                  itemBuilder: (context, index) {
                                    final task = dayTasks[index];
                                    return Card(
                                      elevation: 2,
                                      margin: const EdgeInsets.symmetric(vertical: 6, horizontal: 4),
                                      shape: RoundedRectangleBorder(
                                        borderRadius: BorderRadius.circular(12),
                                      ),
                                      child: InkWell(
                                        onTap: () => _openTaskDetail(task),
                                        borderRadius: BorderRadius.circular(12),
                                        child: Padding(
                                          padding: const EdgeInsets.all(16),
                                          child: Column(
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: [
                                              // 任务标题
                                              Text(
                                                task.title,
                                                style: const TextStyle(
                                                  fontSize: 16,
                                                  fontWeight: FontWeight.w500,
                                                ),
                                                maxLines: 2,
                                                overflow: TextOverflow.ellipsis,
                                              ),
                                              const SizedBox(height: 8),
                                              // 时间和地点
                                              Row(
                                                children: [
                                                  Icon(
                                                    Icons.schedule_rounded,
                                                    size: 16,
                                                    color: Colors.grey[600],
                                                  ),
                                                  const SizedBox(width: 4),
                                                  Text(
                                                    DateFormat('HH:mm').format(task.time),
                                                    style: TextStyle(
                                                      fontSize: 14,
                                                      color: Colors.grey[600],
                                                    ),
                                                  ),
                                                  const SizedBox(width: 16),
                                                  Icon(
                                                    Icons.location_on_rounded,
                                                    size: 16,
                                                    color: Colors.grey[600],
                                                  ),
                                                  const SizedBox(width: 4),
                                                  Expanded(
                                                    child: Text(
                                                      task.location,
                                                      style: TextStyle(
                                                        fontSize: 14,
                                                        color: Colors.grey[600],
                                                      ),
                                                      overflow: TextOverflow.ellipsis,
                                                    ),
                                                  ),
                                                ],
                                              ),
                                              const SizedBox(height: 8),
                                              // 标签行：优先级、分类、备注
                                              SingleChildScrollView(
                                                scrollDirection: Axis.horizontal,
                                                child: Row(
                                                  children: [
                                                    _buildPriorityTag(task.priority),
                                                    const SizedBox(width: 8),
                                                    _buildCategoryTag(task.category),
                                                    if (task.note != null && task.note!.isNotEmpty) ...[
                                                      const SizedBox(width: 8),
                                                      Container(
                                                        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                                                        decoration: BoxDecoration(
                                                          color: Colors.blue.withOpacity(0.1),
                                                          borderRadius: BorderRadius.circular(4),
                                                          border: Border.all(
                                                            color: Colors.blue.withOpacity(0.3),
                                                            width: 1,
                                                          ),
                                                        ),
                                                        child: Row(
                                                          mainAxisSize: MainAxisSize.min,
                                                          children: [
                                                            Icon(
                                                              Icons.note_outlined,
                                                              size: 12,
                                                              color: Colors.blue,
                                                            ),
                                                            const SizedBox(width: 2),
                                                            Text(
                                                              '备注',
                                                              style: TextStyle(
                                                                fontSize: 10,
                                                                color: Colors.blue,
                                                                fontWeight: FontWeight.w500,
                                                              ),
                                                            ),
                                                          ],
                                                        ),
                                                      ),
                                                    ],
                                                  ],
                                                ),
                                              ),
                                            ],
                                          ),
                                        ),
                                      ),
                                    );
                                  },
                                ),
                        ),
                      ],
                    ),
                  ),
                ),
              );
            }),
          ),
        ),
      ],
    );
  }

  // 日视图
  Widget _buildDayView() {
    final dayTasks = _getTasksForDate(_selectedDate);
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    final selectedDate = DateTime(_selectedDate.year, _selectedDate.month, _selectedDate.day);
    final isToday = selectedDate.isAtSameMomentAs(today);

    return Column(
      children: [
        // 日期标题和筛选按钮
        Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: isToday ? Colors.blue.withOpacity(0.1) : Colors.white,
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.05),
                blurRadius: 8,
                offset: const Offset(0, 2),
              ),
            ],
          ),
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    DateFormat('EEEE').format(_selectedDate),
                    style: TextStyle(
                      fontSize: 16,
                      color: isToday ? Colors.blue : Colors.grey[600],
                    ),
                  ),
                  if (!selectedDate.isBefore(today))
                    IconButton(
                      icon: const Icon(Icons.add_circle_outline),
                      onPressed: _addNewTask,
                      color: Colors.blue,
                    ),
                ],
              ),
              const SizedBox(height: 16),
              _buildTaskFilter(),
            ],
          ),
        ),

        // 任务列表
        Expanded(
          child: dayTasks.isEmpty
              ? Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(
                        Icons.event_note,
                        size: 64,
                        color: Colors.grey[300],
                      ),
                      const SizedBox(height: 16),
                      Text(
                        isToday ? '今天没有任务' : '这一天没有任务',
                        style: TextStyle(
                          fontSize: 16,
                          color: Colors.grey[600],
                        ),
                      ),
                    ],
                  ),
                )
              : ListView.builder(
                  padding: const EdgeInsets.all(16),
                  itemCount: dayTasks.length,
                  itemBuilder: (context, index) {
                    final task = dayTasks[index];
                    return Card(
                      elevation: 2,
                      margin: const EdgeInsets.symmetric(vertical: 6, horizontal: 4),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: InkWell(
                        onTap: () => _openTaskDetail(task),
                        borderRadius: BorderRadius.circular(12),
                        child: Padding(
                          padding: const EdgeInsets.all(16),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              // 任务标题
                              Text(
                                task.title,
                                style: TextStyle(
                                  fontSize: 16,
                                  fontWeight: FontWeight.bold,
                                  decoration: task.isCompleted ? TextDecoration.lineThrough : null,
                                  color: task.isCompleted ? Colors.grey : Colors.black,
                                ),
                              ),
                              const SizedBox(height: 8),
                              // 时间和地点
                              Row(
                                children: [
                                  Icon(
                                    Icons.schedule_rounded,
                                    size: 16,
                                    color: Colors.grey[600],
                                  ),
                                  const SizedBox(width: 4),
                                  Text(
                                    DateFormat('HH:mm').format(task.time),
                                    style: TextStyle(
                                      fontSize: 14,
                                      color: Colors.grey[600],
                                    ),
                                  ),
                                  const SizedBox(width: 16),
                                  Icon(
                                    Icons.location_on_rounded,
                                    size: 16,
                                    color: Colors.grey[600],
                                  ),
                                  const SizedBox(width: 4),
                                  Expanded(
                                    child: Text(
                                      task.location,
                                      style: TextStyle(
                                        fontSize: 14,
                                        color: Colors.grey[600],
                                      ),
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 8),
                              // 标签行：优先级、分类、备注
                              SingleChildScrollView(
                                scrollDirection: Axis.horizontal,
                                child: Row(
                                  children: [
                                    _buildPriorityTag(task.priority),
                                    const SizedBox(width: 8),
                                    _buildCategoryTag(task.category),
                                    if (task.note != null && task.note!.isNotEmpty) ...[
                                      const SizedBox(width: 8),
                                      Container(
                                        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                                        decoration: BoxDecoration(
                                          color: Colors.blue.withOpacity(0.1),
                                          borderRadius: BorderRadius.circular(4),
                                          border: Border.all(
                                            color: Colors.blue.withOpacity(0.3),
                                            width: 1,
                                          ),
                                        ),
                                        child: Row(
                                          mainAxisSize: MainAxisSize.min,
                                          children: [
                                            Icon(
                                              Icons.note_outlined,
                                              size: 12,
                                              color: Colors.blue,
                                            ),
                                            const SizedBox(width: 2),
                                            Text(
                                              '备注',
                                              style: TextStyle(
                                                fontSize: 10,
                                                color: Colors.blue,
                                                fontWeight: FontWeight.w500,
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ],
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    );
                  },
                ),
        ),
      ],
    );
  }

  // 打开任务详情
  void _openTaskDetail(Task task) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => TaskDetailPage(
          task: task,
          onTaskUpdate: (updatedTask) {
            setState(() {
              widget.onTaskUpdate(updatedTask);
            });
          },
          onTaskDelete: widget.onTaskDelete,
        ),
      ),
    );
  }

  // 构建优先级标签
  Widget _buildPriorityTag(int priority) {
    Color color;
    String text;
    IconData icon;
    
    switch (priority) {
      case 1:
        color = Colors.green;
        text = '低';
        icon = Icons.keyboard_arrow_down;
        break;
      case 2:
        color = Colors.orange;
        text = '中';
        icon = Icons.remove;
        break;
      case 3:
        color = Colors.red;
        text = '高';
        icon = Icons.keyboard_arrow_up;
        break;
      default:
        color = Colors.grey;
        text = '中';
        icon = Icons.remove;
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(4),
        border: Border.all(
          color: color.withOpacity(0.3),
          width: 1,
        ),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(
            icon,
            size: 12,
            color: color,
          ),
          const SizedBox(width: 2),
          Text(
            text,
            style: TextStyle(
              fontSize: 10,
              color: color,
              fontWeight: FontWeight.w600,
            ),
          ),
        ],
      ),
    );
  }

  // 构建分类标签
  Widget _buildCategoryTag(String category) {
    Color color;
    IconData icon;
    
    switch (category) {
      case 'Personal':
        color = Colors.blue;
        icon = Icons.person;
        break;
      case 'Work':
        color = Colors.purple;
        icon = Icons.work;
        break;
      case 'Private':
        color = Colors.teal;
        icon = Icons.lock;
        break;
      case 'Meeting':
        color = Colors.orange;
        icon = Icons.people;
        break;
      case 'Events':
        color = Colors.pink;
        icon = Icons.event;
        break;
      default:
        color = Colors.grey;
        icon = Icons.label;
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(4),
        border: Border.all(
          color: color.withOpacity(0.3),
          width: 1,
        ),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(
            icon,
            size: 12,
            color: color,
          ),
          const SizedBox(width: 2),
          Text(
            category,
            style: TextStyle(
              fontSize: 10,
              color: color,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
    );
  }
} 